package com.leetcode.partition13;

import java.io.*;

/**
 * @author `RKC`
 * @date 2022/2/5 16:02
 */
public class LC1219黄金矿工 {

    private static final int[][] dirs = {{-1, 0}, {0, 1}, {1, 0}, {0, -1}};
    private static int ans = 0, n = 0, m = 0;
    private static boolean[][] st;
    private static int[][] graph;

    private static final BufferedReader reader = new BufferedReader(new InputStreamReader(System.in));
    private static final BufferedWriter writer = new BufferedWriter(new OutputStreamWriter(System.out));

    public static void main(String[] args) throws IOException {
        String[] ss = reader.readLine().split(" ");
        int n = Integer.parseInt(ss[0]), m = Integer.parseInt(ss[1]);
        int[][] graph = new int[n][m];
        for (int i = 0; i < n; i++) {
            ss = reader.readLine().split(" ");
            for (int j = 0; j < m; j++) graph[i][j] = Integer.parseInt(ss[j]);
        }
        writer.write(getMaximumGold(graph) + "\n");
        writer.flush();
    }

    public static int getMaximumGold(int[][] grid) {
        graph = grid;
        n = grid.length;
        m = grid[0].length;
        st = new boolean[n][m];
        for (int i = 0; i < n; i++) {
            for (int j = 0; j < m; j++) {
                if (grid[i][j] > 0) dfs(i, j, grid[i][j]);
            }
        }
        return ans;
    }

    private static void dfs(int x, int y, int val) {
        ans = Math.max(ans, val);
        st[x][y] = true;
        for (int[] dir : dirs) {
            int nx = x + dir[0], ny = y + dir[1];
            if (nx < 0 || nx >= n || ny < 0 || ny >= m || st[nx][ny] || graph[nx][ny] == 0) continue;
            dfs(nx, ny, val + graph[nx][ny]);
        }
        st[x][y] = false;
    }
}
